package com.witdata.common.service.community.impl;

import com.mybatisflex.core.query.QueryWrapper;
import com.witdata.common.domain.Status;
import com.witdata.common.domain.dto.CommentLikeDto;
import com.witdata.common.exception.GlobalException;
import com.witdata.common.mapper.CommentLikeMapper;
import com.witdata.common.service.community.CommentLikeService;
import com.witdata.common.util.IdUtils;
import com.witdata.mysql.base.service.ArticleCommentBaseService;
import com.witdata.mysql.base.service.ArticleSubCommentBaseService;
import com.witdata.mysql.base.service.CommentLikeBaseService;
import com.witdata.mysql.domain.entity.TCommentLike;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @author LiuQi
 */
@Service
@RequiredArgsConstructor
public class CommentLikeServiceImpl implements CommentLikeService {
    private final IdUtils idUtils;
    private final CommentLikeBaseService commentLikeBaseService;
    private final ArticleCommentBaseService articleCommentBaseService;
    private final ArticleSubCommentBaseService articleSubCommentBaseService;
    @Override
    public void likeComment(Long commentId) {
        Long userId = idUtils.getUserIdByRequest();
        boolean exists_a = articleCommentBaseService.exists(new QueryWrapper().eq("id", commentId));
        boolean exists_b = articleSubCommentBaseService.exists(new QueryWrapper().eq("id", commentId));
        if(!exists_a && !exists_b){
            throw new GlobalException(Status.ARTICLEREVIEWNOTFOUND);
        }
        boolean exists = commentLikeBaseService.exists(new QueryWrapper().eq("comment_id", commentId).eq("user_id", userId));
        if (exists) {
            throw new GlobalException(Status.LIKEERROR);
        }
        TCommentLike tCommentLike = TCommentLike.builder().id(IdUtils.createId()).commentId(commentId).userId(userId).created(LocalDateTime.now()).build();
        commentLikeBaseService.save(tCommentLike);
    }

    @Override
    public void unlikeComment(Long commentId) {
        Long userId = idUtils.getUserIdByRequest();
        if (!commentLikeBaseService.exists(new QueryWrapper().eq("comment_id", commentId).eq("user_id", userId))) {
            throw new GlobalException(Status.UNLIKEERROR);
        }
        boolean remove = commentLikeBaseService.remove(new QueryWrapper().eq("comment_id", commentId));
        if (!remove) throw new GlobalException(Status.CANCELSUCCESS);
    }

    @Override
    public List<CommentLikeDto> getCommentLikeList() {
        Long userId = idUtils.getUserIdByRequest();
        List<TCommentLike> tCommentLikeList = commentLikeBaseService.list( new QueryWrapper().eq("user_id", userId));
        return CommentLikeMapper.INSTANCE.toCommentLikeDtoList(tCommentLikeList);
    }
}
